<?php

namespace App\Models\lin;

use App\Exceptions\lin\LinException;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\Models\lin\LinGroup
 *
 * @method static \Illuminate\Database\Eloquent\Builder|LinGroup newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|LinGroup newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|LinGroup query()
 * @mixin \Eloquent
 * @property int $id
 * @property string $name 分组名称，例如：搬砖者
 * @property string|null $info 分组信息：例如：搬砖的人
 * @property int $level 分组级别 1：root 2：guest 3：user  root（root、guest分组只能存在一个)
 * @property string $create_time
 * @property string $update_time
 * @property string|null $delete_time
 * @method static \Illuminate\Database\Eloquent\Builder|LinGroup whereCreateTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|LinGroup whereDeleteTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|LinGroup whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|LinGroup whereInfo($value)
 * @method static \Illuminate\Database\Eloquent\Builder|LinGroup whereLevel($value)
 * @method static \Illuminate\Database\Eloquent\Builder|LinGroup whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|LinGroup whereUpdateTime($value)
 * @property-read Collection|LinPermission[] $permission
 * @property-read int|null $permission_count
 * @method static \Illuminate\Database\Query\Builder|LinGroup onlyTrashed()
 * @method static \Illuminate\Database\Query\Builder|LinGroup withTrashed()
 * @method static \Illuminate\Database\Query\Builder|LinGroup withoutTrashed()
 */
class LinGroup extends BaseModel
{
    use SoftDeletes;

    protected $table = 'lin_group';

    protected $fillable = ['name', 'info', 'level'];
    protected $hidden = ['pivot', 'create_time', 'update_time', 'delete_time'];

    public static function createGroup($params)
    {
        if (!empty($params['permission_ids'])){
            foreach ($params['permission_ids'] as $permission_id){
                $permission = LinPermission::find($permission_id);
                if (!$permission) throw new LinException(10231,404);
            }
        }
        return self::create($params)->permissions()->syncWithoutDetaching($params['permission_ids']);
    }

    public static function updateGroup($params)
    {
        $group = self::find($params['id']);
        if (!$group) throw new LinException(10024,404);
        return $group->update($params);
    }

    /**
     * @return BelongsToMany
     */
    public function permissions(): BelongsToMany
    {
        return $this->belongsToMany('App\Models\lin\LinPermission', 'lin_group_permission', 'group_id', 'permission_id');
    }

    public function getLevelAttribute($value)
    {
        $level = [1 => "ROOT", 2 => "GUEST", 3 => "USER"];
        return $level[$value];
    }
}
